package com.event.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhangbo
 * @program: event-plus
 * @ClassName EventClassScanner
 * @description: $
 * @date 2024-07-01 14:08:37
 */
@Component
public class EventClassScanner {

    protected final Log logger = LogFactory.getLog(getClass());


    public Map<String, Class<?>> scanEventAnnotation(String basePackage, Class<? extends Annotation> annotation) {
        // init
        Map<String, Class<?>> map = new LinkedHashMap<>();

        // 获取 annotation 所有符合过滤器条件的所有类对象，封装成map
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(annotation));
        scanner.findCandidateComponents(basePackage).forEach(beanDefinition -> {
            try {
                Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());
                map.put(clazz.getName(), clazz);
            } catch (ClassNotFoundException e) {
                logger.error("解析event事件监听类错误：" + e);
            }
        });
        return map;
    }
}
